package proj.server;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import proj.common.Novel;

public class NovelManager {
	private List<Novel> novels = new ArrayList<>(0);
	public final String NOVEL_NAME = "server/novels.xml";

	public NovelManager() {
		// 从对应的文件中恢复已经存在的小说信息
		// 采用对象序列化为xml的方案
		try {
			XMLDecoder xd = new XMLDecoder(new FileInputStream(NOVEL_NAME));
			novels = (List<Novel>) xd.readObject();
			xd.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

	public List<Novel> getNovels() {
		return this.novels;
	}

	public void addNovel(Novel n) {
		this.novels.add(n);
		// 立即保存到xml
		try {
			XMLEncoder xe = new XMLEncoder(new FileOutputStream(NOVEL_NAME));
			xe.writeObject(this.novels);
			xe.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}
